<template>
  <div>
    <div class="top-panel__box">
      <el-form
        :model="dataForm"
        ref="dataForm"
        inline
        size="small"
        onsubmit="return false"
      >
        <el-row>
          <el-col :span="24" style="margin-bottom:15px;">
            <el-form-item label="产品类型" label-width="80px">
              <el-select
                placeholder="产品类型"
                v-model="dataForm.productTypeList"
                multiple
                clearable
                collapse-tags
              >
                <el-option
                  v-for="(value, key) of dicts['product_type'].childMap"
                  :key="key"
                  :label="value"
                  :value="key"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input
                placeholder="输入进件编号/姓名"
                v-model="dataForm.freeCondition"
                maxlength="30"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-input
                placeholder="受理人"
                v-model="dataForm.acceptorName"
                maxlength="30"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-date-picker
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd"
                v-model="dataForm.beginTime"
                style="width:220px"
                placeholder="任务创建时间起"
              />
              <span>-</span>
              <el-date-picker
                type="date"
                @change="endChange"
                v-model="dataForm.endTime"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                style="width:220px"
                placeholder="任务创建时间止"
              />
            </el-form-item>
            <el-form-item label="全部状态" label-width="80px">
              <el-select
                placeholder="全部状态"
                v-model="dataForm.followStatus"
                clearable
              >
                <el-option
                  v-for="(value, key) in dicts['mortgage_status'].childMap"
                  :key="key"
                  :label="value"
                  :value="key"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item>
              <el-button type="primary" @click="getList(1)">
                <fa-icon class="fa-search" />查询</el-button
              >
              <reset-button
                :dataForm.sync="dataForm"
                :fixedData="{ pageNum: 1, pageSize: 10 }"
              />
              <el-button type="primary" @click="batchAssign('cancel')"
                >批量撤回</el-button
              >
              <el-button type="primary" @click="batchAssign('assign')"
                >批量分派</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-row class="table-top">
      <el-table
        :border="true"
        :row-key="getRowKey"
        @select-all="selectAllEvent"
        :data="dataList"
        v-loading="tableLoading"
        tooltip-effect="light"
        @selection-change="handleSelectionChange"
        :cell-style="addCellStyle"
        class="tc-table-box"
        size="small"
      >
        <el-table-column
          type="selection"
          width="55"
          fixed="left"
        ></el-table-column>
        <el-table-column
          type="index"
          width="55"
          fixed="left"
          label="序号"
        ></el-table-column>
        <template v-for="(column, index) in FOLLOW_HEAD_LIST">
          <el-table-column
            :prop="column.prop"
            :label="column.label"
            :key="index"
            :width="column.width"
            :show-overflow-tooltip="true"
          />
        </template>
        <el-table-column
          fixed="right"
          class-name="oper-col"
          width="200"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="apportionEvent(scope.row, 'PROCESSING')"
              v-if="
                scope.row.acceptorName &&
                  scope.row.followStatus != 'AUDIT' &&
                  scope.row.followStatus != 'IMPLEMENTED'
              "
            >
              撤回
            </el-button>
            <el-button
              type="text"
              @click="apportionEvent(scope.row, 'WAIT_ASSIGN')"
              v-if="
                !scope.row.acceptorName &&
                  scope.row.followStatus != 'AUDIT' &&
                    scope.row.followStatus != 'IMPLEMENTED'
              "
            >
              分派
            </el-button>
            <el-button
              type="text"
              @click="showDetails(scope.row)"
              v-if="
                scope.row.followStatus === 'AUDIT' ||
                  scope.row.followStatus === 'IMPLEMENTED'
              "
            >
              详情
            </el-button>
            <el-button
              type="text"
              v-if="
                scope.row.followStatus != 'AUDIT' &&
                  scope.row.followStatus != 'IMPLEMENTED'
              "
              @click="showDownloadApplyWindow(scope.row)"
            >
              合同材料
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row class="pagination-top">
        <pagination
          :pageNum.sync="dataForm.pageNum"
          :curSizes.sync="dataForm.pageSize"
          :total="total"
          @getList="getList"
        />
      </el-row>
    </el-row>
    <!-- 下载合同材料 -->
    <el-dialog title="合同材料" :visible.sync="showDownloadApplyChartWindow" width="30%" >
      <div v-if="showDownloadApplyChartWindow">
        <el-row>
          <el-col>
            <i class="el-icon-question" style="color: #409EFE"></i>
            <span style="font-size: 15px; font-weight:bold">请选择业务所属地区</span>
          </el-col>
        </el-row>
        <el-row style="margin-top: 20px; margin-bottom: 20px" type="flex" :gutter="20" justify="center">
          <el-col :span="5">
            <el-button style="width: 100%" type="primary" size="small" @click="downloanApplyChart('CHANGCHUN')">长春</el-button>
          </el-col>
          <el-col :span="5">
            <el-button style="width: 100%" type="primary" size="small" @click="downloanApplyChart('JILIN')">吉林</el-button>
          </el-col>
          <el-col :span="5">
            <el-button style="width: 100%" type="primary" size="small" @click="downloanApplyChart('DALIAN')">大连</el-button>
          </el-col>
          <el-col :span="5">
            <el-button style="width: 100%" type="primary" size="small" @click="downloanApplyChart('OTHER')">其他</el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
    <!-- 下载合同材料 - 具体材料分类-->
    <el-dialog title="合同材料" 
      :visible.sync="showDownloadListWindow" 
      width="45%" 
      @close="getList"
      :close-on-click-modal="false">
      <DownLoadList
        :caseId="nowCaseId"
        v-if="showDownloadListWindow" 
        :city="downLoadFlag"
        :rowData="downLoadRow"
        ></DownLoadList>
    </el-dialog>
    <!--编辑-->
    <el-dialog
      title="分派"
      :visible.sync="showWaitAssign"
      width="45%"
      :close-on-click-modal="false"
    >
      <wait-assign
        v-if="showWaitAssign"
        @updataSuccess="getWaitAssigner"
        @close="closeLoanDetail"
      ></wait-assign>
    </el-dialog>
    <!-- 落实抵押详情 -->
    <el-dialog
      title="落实抵押详情"
      :visible.sync="showDetailsDialog"
      width="65%"
      :close-on-click-modal="false"
    >
      <imMortgage-Details
        v-if="showDetailsDialog"
        :productType="productType"
        :followId="nowResearchId"
        :caseId="nowCaseId"
        @close="closeDetails"
      ></imMortgage-Details>
    </el-dialog>
  </div>
</template>

<script>
import api from "./api";
import { CONSTANT_OBJ } from "@/utils/constant";
import { mapState } from "vuex";
import { FOLLOW_HEAD_LIST } from "./js/contant.js";
import OrganizationCascader from "@/components/organizationCascader";
import WaitAssign from "./components/WaitAssign";
import imMortgageDetails from "./components/imMortgageDetails";
import DownLoadList from "./components/DownLoadList.vue";
import { common } from "@/utils/common";
import { disposePhone, encryptName, downloadWord } from "@/utils/util";
export default {
  components: { OrganizationCascader, WaitAssign, imMortgageDetails, DownLoadList },
  data() {
    return {
      FOLLOW_HEAD_LIST,
      tableLoading: false,
      showWaitAssign: false,
      showDetailsDialog: false,
      selectIds: [],
      slectedList: [],
      nowCaseId: "",
      nowResearchId: "",
      dataForm: {
        acceptorName: "",
        beginTime: "",
        endTime: "",
        customerName: "",
        productTypeList: [],
        followStatus: "",
        freeCondition: "",
        pageNum: 1,
        pageSize: 10
      },
      dataList: [],
      editorDialog: false,
      total: 0,
      productNoList: [],
      editData: {},
      uploadDialog: false,
      productType: "",
      showDownloadApplyChartWindow: false,
      showDownloadListWindow: false,
      downLoadFlag: '',
      downLoadRow: {}
    };
  },
  mounted() {
    this.getList();
    console.log("this.dicts", this.dicts);
  },
  methods: {
    // 查询列表
    getList(val) {
      if (!this.rulesTime()) return;
      this.dataForm.pageNum = val || this.dataForm.pageNum;
      this.tableLoading = true;
      api
        .queryByPageCondition(this.dataForm)
        .then(res => {
          const { responseCode, data } = res;
          if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
            this.dataList = [...data.list] || [];
            console.log(this.dataList);
            this.dataList.forEach(item => {
              let statusUpdateTime = new Date(item.statusUpdateTime).getTime();
              let newTime = new Date().getTime();
              let statusStopTime = `${parseInt(
                (newTime - statusUpdateTime) / 60000
              )}min`;
              item.statusStopTime = statusStopTime;
              item.newPhone = disposePhone(item.customerPhone);
              item.newName = encryptName(item.customerName);
            });
            this.dataList = [...this.disoseStatus(this.dataList)];
            console.log(this.dataList);
            this.total = parseInt(data.total) || 0;
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    /**
     * @description 当前状态停留时间：若大于60min，则标记为红色
     */
    addCellStyle({ row: { statusStopTime }, column: { property } }) {
      if (parseInt(statusStopTime) > 60 && property === "statusStopTime") {
        return "color: red";
      }
    },
    disoseStatus(list) {
      return list.map(ele => {
        this.dicts.mortgage_status.childList.forEach(v => {
          if (ele.followStatus === v.dictNo) {
            ele.newStatus = v.dictName;
          }
        });
        this.dicts.product_type.childList.forEach(v => {
          if (ele.productType === v.dictNo) {
            ele.newProductType = v.dictName;
          }
        });
        return ele;
      });
    },
    handleSelectionChange(row) {
      console.log(row);
      this.slectedList = row;
      let ids = this.slectedList.map(ele => ele.followId);
      this.selectIds = [...ids];
    },
    showEditor(row) {
      this.editorDialog = true;
      this.editData = { ...row };
    },
    close(data) {
      console.log(data);
      this.editorDialog = data;
    },
    enterPersonInfo() {
      common.confirmFn("", "是否确认分派代理人").then(res => {
        if (res) {
          console.log("确认成功");
        }
      });
    },
    deletPersonInfo() {
      common
        .confirmFn("撤回后您可重新进行分派", "是否确定撤回分派？")
        .then(res => {
          if (res) {
            console.log("删除成功");
            api.assignCancel({ followIds: this.selectIds }).then(res => {
              this.successFn(res);
            });
          }
        });
    },
    showUpload() {
      this.uploadDialog = true;
    },
    closeUpload(res) {
      this.uploadDialog = res;
    },
    showDetails(item) {
      this.nowCaseId = item.caseId;
      this.nowResearchId = item.followId;
      this.productType = item.productType;
      console.log(item, "内容");
      // return
      this.showDetailsDialog = true;
    },
    closeDetails(val) {
      this.showDetailsDialog = false;
    },
    apportionEvent(item, type) {
      this.selectIds = [item.followId];
      switch (type) {
        case "WAIT_ASSIGN":
          this.showWaitAssign = true;
          break;
        case "PROCESSING":
          this.deletPersonInfo();
          break;
      }
    },
    /**
     * @description 批量分派/撤回
     */
    batchAssign(type) {
      if (this.selectIds.length === 0) {
        this.$message.error("请选择至少一份案件");
        return;
      }
      switch (type) {
        case "assign":
          this.disposeBatchData();
          break;
        case "cancel":
          this.disposeCancelData();
          break;
      }
    },
    disposeCancelData() {
      let ids = this.filterData(this.slectedList);
      console.log(ids, "数据处理");
      if (ids.failIndex > 0) {
        common
          .confirmFn(
            `当前已选中进件 ${this.slectedList.length} 笔，其中可撤回分派进件 ${ids.failIndex} 笔。`,
            "是否确定批量撤回分派？"
          )
          .then(res => {
            if (res) {
              api.cancelResearch({ followIds: ids.failIds }).then(res => {
                this.successFn(res);
              });
            }
          });
      } else {
        common
          .confirmFn(`当前选中的进件中无可撤回分派进件。`, "无可撤回进件")
          .then(res => {
            if (res) {
            }
          });
      }
    },
    disposeBatchData() {
      let ids = this.filterData(this.slectedList);
      if (ids.successIndex > 0) {
        common
          .confirmFn(
            `当前已选中进件 ${this.slectedList.length} 笔，其中可分派进件 ${ids.successIndex} 笔。`,
            "是否确定批量分派？"
          )
          .then(res => {
            if (res) {
              this.selectIds = [...ids.successIds];
              this.showWaitAssign = true;
            }
          });
      } else {
        common
          .confirmFn(`当前选中的进件中无可分派进件。`, "无可分派进件")
          .then(res => {
            if (res) {
            }
          });
      }
    },
    selectAllEvent(selection) {
      this.slectedList = [...selection];
    },
    // 处理数据
    filterData(ids) {
      let checked = ids.filter(
        v => v.followStatus !== "COMPLETED" && !v.acceptorName
      );
      let notCheck = ids.filter(
        v => v.followStatus !== "COMPLETED" && v.acceptorName
      );
      console.log(checked, "可分派");
      console.log(notCheck, "不可分派");
      let successIndex = checked.length;
      let failIndex = notCheck.length;
      let successIds = checked.map(ele => ele.followId);
      let failIds = notCheck.map(ele => ele.followId);
      return {
        successIndex,
        failIndex,
        failIds,
        successIds
      };
    },
    getWaitAssigner(val) {
      console.log(val, "获取分派人");
      let params = {
        acceptorId: val,
        followIds: [...this.selectIds]
      };
      console.log(params, "分派受理人");
      api.assignAcceptor(params).then(res => {
        this.successFn(res, "showWaitAssign");
      });
    },
    successFn(res, dialog) {
      const { responseCode, responseMsg: message } = res;
      if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
        this.$message({
          message,
          type: "success"
        });
        if (dialog) {
          this[dialog] = false;
        }
        this.selectedIds = [];
        this.slectedList = [];
        this.getList(1);
      }
    },
    closeLoanDetail(val) {
      this.showWaitAssign = val;
    },
    endChange(end) {
      this.dataForm.endTime = end == null ? end : `${end} 23:59:59`;
    },
    getRowKey(row) {
      return row.followId;
    },
    rulesTime() {
      let tempStart = this.dataForm.beginTime;
      let tempEnd = this.dataForm.endTime;
      let start = new Date(tempStart).getTime() || "";
      let end = new Date(tempEnd).getTime() || "";
      if (start && end) {
        if (start > end) {
          this.$message.error("结束时间不能小于开始时间");
          return false;
        } else {
          return true;
        }
      }
      return true;
    },
    // 下载
    downloadFile(no, caseId, assetId, name){
      let parmas = {
        caseId: caseId || '',
        contractTemplateNo: no || '',
        assetId: assetId || ''
      }
      let path = `/v1/api/esale-case/house/mortgage/loan/mortgage/download/contract`
      downloadWord(path, parmas, name)
    },
    // 显示下载申请表弹窗
    showDownloadApplyWindow (row) {
      this.downLoadRow = row
      this.nowCaseId = row.caseId
      if (row.city) {
        this.downloanApplyChart(row.city)
      } else  {
        this.showDownloadApplyChartWindow = true
      }
    },
    // 下载申请表
    downloanApplyChart (flag) {
        this.downLoadFlag = flag
        this.showDownloadApplyChartWindow = false
        this.showDownloadListWindow = true
    },
  },
  computed: {
    ...mapState({
      dicts: state => state.common.dicts
    })
  }
};
</script>
<style lang="less">
@import "../../assets/css/common.less";
.tc-table-box {
  border: 1px solid @main-border-color;
  border-bottom: none;
  width: 100%;
}

.el-table-box thead {
  color: #707277;
}
.tc-table-box th {
  background-color: @panel-color !important;
}
</style>
